#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

"""
Functions that assist with the formatting, parsing, or display for records.
"""

import re
import types
import utility
import urlcheck

def parsecreator(text):
	"""
	Parse the creator text, return a list of authors if successful.
	"""
	# misc info in creator
	#  (what the initials stand for)
	text = re.sub(r'(?u)\(.+?\)', '', text)
	#  [profession]
	text = re.sub(r'(?u)\[.+?\]', '', text)
	#  -year-
	text = re.sub(r'(?u)-\d+-', '', text)
	# b. year.
	text = re.sub(r'(?u)\bb\. \d+\.?', '', text)
	#  year-range	# the second part of the range may be missing
	text = re.sub(r'(?u)\d+-(\d+)?', '', text)
	#  email@address.dom
	text = re.sub(r'(?u)\b[A-Za-z0-9.-_]+@[A-Za-z0-9.-]+\.[A-Za-z.]+\b', '', text)

	# escape html escapes
	text = re.sub(r'&#(\d)+;', '&#&\\1&#&', text)

	# remove newlines, duplicates, extra whitespace
	text = re.sub(r'(?u)\n', ';', text)
	text = re.sub(r'(?u)(;|,)\s*(;|,)', ';', text)
	text = re.sub(r'(?u)\s*;(\s*;)?\s*', '; ', text)

	# split field, common delimiters ;
	creatorsraw = re.split('\s*;\s*', text)

	# list to add good creators to
	creators = []

	# dump empty/bad creators
	for creator in creatorsraw:
		# minimum length of 3
		if len(creator.strip()) > 2:
			# unescape html espaces
			creator = re.sub(r'&#&(\d+)?&#&', '&#\\1;', creator)
			creators.append(creator)

	# check for odd creator format (only 1 parsed)
	if len(creators) == 1:
		# reevaluate the creators list
		text = creators[0]

		# check to see if possible comma delimited names
		counter = { ',':0, ';':0, ' ':0 }

		# format text for difficult detection, force space after comma, strip whitespace
		text = re.sub(',\s*', ', ', text)
		text = text.strip()

		for char in text:
			# increment count if present, otherwise start at 1
			counter[char] = counter.get(char, 0) + 1

		# if no high level delimiters were found
		if counter[';'] == 0:
			# and multiple low level delimiters are present
			if counter[','] > 1 or (counter[' '] > 2 and counter[','] == 1):
				# split on comma
				creators = re.split('\s*,\s*', text)

	# return creator list
	return creators


def linkcreator(text, creators):
	"""
	Parse for creators in the text and add links to search for each creator.
	"""
	# link template
	template = """<a class="noul authorlink" href='search.py?s=author:"%s"'>%s</a>"""

	# link each creator

	# if dict was passed
	if type(creators) == types.DictType:
		# bold only anchor text
		for creator, boldcreator in creators.iteritems():
			# create linksafe creator
			creatorsafe = creator.replace("'", "&apos;")
			# add links
			text = text.replace(creator, template % (creatorsafe, boldcreator))
	
	# if list was passed
	if type(creators) == types.ListType:
		# no bold, link only
		for creator in creators:
			# create linksafe creator
			creatorsafe = creator.replace("'", "&apos;")
			# add links
			text = text.replace(creator, template % (creatorsafe, creator))

	# return string
	return text


def outfieldlong(label, field):
	"""
	Return a string containing a table row for expanded output.
	"""
	# the row return string
	row = ''

	# if field isn't empty
	if not utility.empty(field):
		# add the table row info
		row += """<tr><td class="expand_bg">%s:</td>""" % label

		# add links to the field
		field = urlcheck.linkify(field)

		# add line breaks where needed
		field = field.replace('\n', '<br>')

		# append field to row
		row += """<td>%s</td></tr>""" % field

	# return table row
	return row

# eof

